<template>
	<view class="recent-push-page">
		<!-- 顶部导航栏 -->
		<uni-nav-bar 
			dark 
			:fixed="true" 
			status-bar 
			left-icon="left" 
			left-text="返回" 
			title="近期推送" 
			@clickLeft="goBack" 
		/>
		
		<view class="container">
			<!-- 筛选器和批量操作 -->
			<view class="filter-section">
				<view class="filter-row">
					<view class="filter-group">
						<text class="filter-label">开始日期:</text>
						<picker mode="date" :value="filterStartDate" @change="onStartDateChange">
							<view class="filter-input">{{ filterStartDate || '选择日期' }}</view>
						</picker>
					</view>
					<view class="filter-group">
						<text class="filter-label">结束日期:</text>
						<picker mode="date" :value="filterEndDate" @change="onEndDateChange">
							<view class="filter-input">{{ filterEndDate || '选择日期' }}</view>
						</picker>
					</view>
				</view>
				<view class="filter-row">
					<view class="filter-group">
						<text class="filter-label">每页条数:</text>
						<picker :range="pageSizeOptions" range-key="label" :value="pageSizeIndex" @change="onPageSizeChange">
							<view class="filter-input">{{ pageSizeOptions[pageSizeIndex].label }}</view>
						</picker>
					</view>
					<view class="filter-actions">
						<button @click="applyFilter" class="filter-btn">筛选</button>
						<button @click="resetFilter" class="filter-btn secondary">重置</button>
					</view>
				</view>
				<view class="bulk-actions">
					<button @click="markAllAsRead" class="bulk-btn">标记当前筛选结果已读</button>
					<button @click="markAllRecordsAsRead" class="bulk-btn primary">标记所有已读</button>
				</view>
			</view>
			
			<!-- 统计信息 -->
			<view class="stats-card">
				<view class="stat-item">
					<text class="stat-label">总推送</text>
					<text class="stat-value">{{ pushStats.total }}</text>
				</view>
			<view class="stat-item">
				<text class="stat-label">已读</text>
				<text class="stat-value read">{{ pushStats.read }}</text>
			</view>
			<view class="stat-item">
				<text class="stat-label">未读</text>
				<text class="stat-value unread">{{ pushStats.unread }}</text>
			</view>
			</view>

			<!-- 推送列表 -->
			<view class="push-list">
				<view v-if="loading" class="loading-container">
					<text class="loading-text">加载中...</text>
				</view>
				
				<view v-else-if="pushRecords.length === 0" class="empty-state">
					<text class="empty-icon">🔔</text>
					<text class="empty-title">暂无推送记录</text>
					<text class="empty-subtitle">当有符合你偏好的任务时，会在这里显示</text>
				</view>
				
				<view v-else>
					<view 
						v-for="record in pushRecords" 
						:key="record.id" 
						class="push-item"
						:class="{ 'read': record.readTime }"
					>
						<view class="push-header">
							<view class="push-info">
								<text class="task-title">{{ record.taskTitle }}</text>
								<text class="push-time">{{ formatTime(record.pushTime) }}</text>
							</view>
							<view class="push-status">
								<text 
									class="status-badge" 
									:class="getDisplayStatusClass(record)"
								>
									{{ getDisplayStatusText(record) }}
								</text>
							</view>
						</view>
						
						<view class="push-content">
							<text class="task-description">{{ record.taskDescription }}</text>
						</view>
						
						<view class="push-footer">
							<view class="push-meta">
								<text class="meta-item">💰 {{ record.taskReward || '面议' }}</text>
								<text class="meta-item">📍 {{ record.taskLocation || '不限地点' }}</text>
								<text v-if="record.taskDeadline" class="meta-item">
									⏰ {{ formatDeadline(record.taskDeadline) }}
								</text>
							</view>
							<view class="push-actions">
								<button 
									v-if="!record.readTime" 
									@click.stop="markAsRead(record.id)"
									class="action-btn read-btn"
								>
									标记已读
								</button>
								<button 
									@click.stop="goToTaskDetail(record)"
									class="action-btn detail-btn"
								>
									查看任务
								</button>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 分页控件 -->
				<view v-if="totalPages > 1" class="pagination">
					<button @click="goToPage(1)" :disabled="currentPage === 1" class="page-btn">首页</button>
					<button @click="goToPage(currentPage - 1)" :disabled="currentPage === 1" class="page-btn">上一页</button>
					<view class="page-info">
						<text>第 {{ currentPage }} / {{ totalPages }} 页</text>
					</view>
					<button @click="goToPage(currentPage + 1)" :disabled="currentPage === totalPages" class="page-btn">下一页</button>
					<button @click="goToPage(totalPages)" :disabled="currentPage === totalPages" class="page-btn">末页</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useUserStore } from '@/store/user';
import { NETWORK_CONFIG } from '@/config/network.js';

const userStore = useUserStore();
const pushRecords = ref([]);
const pushStats = ref({
	total: 0,
	read: 0,
	unread: 0
});
const loading = ref(false);

// 筛选相关
const filterStartDate = ref('');
const filterEndDate = ref('');

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const totalPages = ref(1);
const totalRecords = ref(0);

const pageSizeOptions = ref([
	{ label: '5条/页', value: 5 },
	{ label: '10条/页', value: 10 },
	{ label: '20条/页', value: 20 },
	{ label: '50条/页', value: 50 }
]);
const pageSizeIndex = ref(1); // 默认选择10条

// 返回上一页
const goBack = () => {
	uni.navigateBack();
};

// 加载推送记录
const loadPushRecords = async () => {
	loading.value = true;
	try {
		const token = uni.getStorageSync('accessToken');
		
		// 计算偏移量
		const offset = (currentPage.value - 1) * pageSize.value;
		
		// 构建请求参数
		const params = {
			offset: offset,
			limit: pageSize.value
		};
		
		// 添加时间筛选参数
		if (filterStartDate.value) {
			params.startDate = filterStartDate.value;
		}
		if (filterEndDate.value) {
			params.endDate = filterEndDate.value;
		}
		
		const res = await uni.request({
			url: `${NETWORK_CONFIG.API_BASE_URL}/api/push/recent`,
			method: 'GET',
			header: {
				'Access-Token': `Bearer ${token}`
			},
			data: params
		});
		
		if (res.data.success) {
			pushRecords.value = res.data.data || [];
			totalRecords.value = res.data.total || pushRecords.value.length;
			totalPages.value = Math.ceil(totalRecords.value / pageSize.value);
			if (totalPages.value === 0) totalPages.value = 1;
			
			// 如果当前页超出总页数，跳转到第一页
			if (currentPage.value > totalPages.value && totalPages.value > 0) {
				currentPage.value = 1;
				loadPushRecords();
				return;
			}
			
			updateStats();
		} else {
			uni.showToast({
				title: res.data.message || '获取推送记录失败',
				icon: 'none'
			});
		}
	} catch (error) {
		console.error('获取推送记录失败:', error);
		uni.showToast({
			title: '网络错误',
			icon: 'none'
		});
	} finally {
		loading.value = false;
	}
};

// 更新统计信息
const updateStats = () => {
	pushStats.value.total = pushRecords.value.length;
	pushStats.value.read = pushRecords.value.filter(r => r.readTime).length;
	pushStats.value.unread = pushRecords.value.filter(r => !r.readTime).length;
};

// 跳转到任务详情并标记为已读
const goToTaskDetail = async (record) => {
	try {
		// 如果未读，先标记为已读
		if (!record.readTime) {
			await markAsRead(record.id, true);
		}
		
		// 跳转到任务详情
		if (record.taskId) {
			uni.navigateTo({
				url: `/pages/task/detail/index?id=${record.taskId}`,
				fail: (err) => {
					console.error('跳转到任务详情失败:', err);
					uni.showToast({
						title: '页面跳转失败',
						icon: 'none'
					});
				}
			});
		} else {
			uni.showToast({
				title: '任务ID缺失',
				icon: 'none'
			});
		}
	} catch (error) {
		console.error('处理跳转失败:', error);
		// 即使标记失败也跳转
		if (record.taskId) {
			uni.navigateTo({
				url: `/pages/task/detail/index?id=${record.taskId}`
			});
		}
	}
};

// 标记为已读（静默模式，不显示提示）
const markAsRead = async (pushRecordId, silent = false) => {
	try {
		const token = uni.getStorageSync('accessToken');
		const res = await uni.request({
			url: `${NETWORK_CONFIG.API_BASE_URL}/api/push/read`,
			method: 'POST',
			header: {
				'Content-Type': 'application/json',
				'Access-Token': `Bearer ${token}`
			},
			data: {
				pushRecordId: pushRecordId,
				userId: userStore.profile?.uid
			}
		});
		
		if (res.data.success) {
			// 更新本地数据
			const record = pushRecords.value.find(r => r.id === pushRecordId);
			if (record) {
				record.readTime = new Date().toISOString();
				updateStats();
			}
			
			// 触发全局事件，通知主页面刷新未读数量
			uni.$emit('push-record-read');
			
			// 非静默模式才显示提示
			if (!silent) {
				uni.showToast({
					title: '标记已读成功',
					icon: 'success'
				});
			}
		} else {
			if (!silent) {
				uni.showToast({
					title: res.data.message || '标记失败',
					icon: 'none'
				});
			}
		}
	} catch (error) {
		console.error('标记已读失败:', error);
		if (!silent) {
			uni.showToast({
				title: '网络错误',
				icon: 'none'
			});
		}
	}
};

// 格式化时间
const formatTime = (timeStr) => {
	if (!timeStr) return '未知时间';
	
	const time = new Date(timeStr);
	const now = new Date();
	const diff = now - time;
	
	if (diff < 60000) { // 1分钟内
		return '刚刚';
	} else if (diff < 3600000) { // 1小时内
		return `${Math.floor(diff / 60000)}分钟前`;
	} else if (diff < 86400000) { // 1天内
		return `${Math.floor(diff / 3600000)}小时前`;
	} else if (diff < 604800000) { // 1周内
		return `${Math.floor(diff / 86400000)}天前`;
	} else {
		return time.toLocaleDateString();
	}
};

// 格式化截止时间
const formatDeadline = (deadlineStr) => {
	if (!deadlineStr) return '';
	
	const deadline = new Date(deadlineStr);
	const now = new Date();
	const diff = deadline - now;
	
	if (diff < 0) {
		return '已过期';
	} else if (diff < 86400000) { // 1天内
		return `${Math.floor(diff / 3600000)}小时后截止`;
	} else {
		return `${Math.floor(diff / 86400000)}天后截止`;
	}
};

// 获取显示状态样式类（根据readTime）
const getDisplayStatusClass = (record) => {
	if (record.readTime) {
		return 'status-read'; // 已读
	}
	return 'status-pending'; // 未读
};

// 获取显示状态文本（根据readTime）
const getDisplayStatusText = (record) => {
	if (record.readTime) {
		return '已读';
	}
	return '未读';
};

// 筛选器事件处理
const onStartDateChange = (e) => {
	filterStartDate.value = e.detail.value;
};

const onEndDateChange = (e) => {
	filterEndDate.value = e.detail.value;
};

const onPageSizeChange = (e) => {
	pageSizeIndex.value = e.detail.value;
	pageSize.value = pageSizeOptions.value[e.detail.value].value;
	currentPage.value = 1; // 切换每页条数时重置到第一页
	loadPushRecords();
};

const applyFilter = () => {
	currentPage.value = 1;
	loadPushRecords();
};

const resetFilter = () => {
	filterStartDate.value = '';
	filterEndDate.value = '';
	currentPage.value = 1;
	pageSize.value = 10;
	pageSizeIndex.value = 1;
	loadPushRecords();
};

// 分页事件处理
const goToPage = (page) => {
	if (page < 1 || page > totalPages.value) return;
	currentPage.value = page;
	loadPushRecords();
};

// 批量标记已读
const markAllAsRead = async () => {
	// 只标记当前筛选结果中的未读记录
	const unreadRecords = pushRecords.value.filter(r => !r.readTime);
	
		if (unreadRecords.length === 0) {
			uni.showToast({
				title: '当前筛选结果中已全部标记已读',
				icon: 'none'
			});
			return;
		}
	
	uni.showModal({
		title: '确认',
		content: `确定要标记当前筛选结果中的 ${unreadRecords.length} 条记录为已读吗？`,
		success: async (res) => {
			if (res.confirm) {
				// 批量标记为已读
				for (const record of unreadRecords) {
					await markAsRead(record.id, true);
				}
				
				uni.showToast({
					title: `成功标记 ${unreadRecords.length} 条记录为已读`,
					icon: 'success'
				});
				
				// 刷新列表
				loadPushRecords();
			}
		}
	});
};

// 标记所有推送记录为已读
const markAllRecordsAsRead = async () => {
	uni.showModal({
		title: '确认',
		content: '确定要标记所有推送记录为已读吗？此操作将影响所有历史记录。',
		success: async (res) => {
			if (res.confirm) {
				try {
					const token = uni.getStorageSync('accessToken');
					const response = await uni.request({
						url: `${NETWORK_CONFIG.API_BASE_URL}/api/push/mark-all-read`,
						method: 'POST',
						header: {
							'Content-Type': 'application/json',
							'Access-Token': `Bearer ${token}`
						},
						data: {
							userId: userStore.profile?.uid
						}
					});
					
					if (response.data.success) {
						uni.showToast({
							title: '所有记录已标记为已读',
							icon: 'success'
						});
						
						// 刷新列表
						loadPushRecords();
						
						// 触发全局事件
						uni.$emit('push-record-read');
					} else {
						uni.showToast({
							title: response.data.message || '标记失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('标记所有记录已读失败:', error);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				}
			}
		}
	});
};

onMounted(() => {
	loadPushRecords();
});
</script>

<style scoped>
.recent-push-page {
	min-height: 100vh;
	background-color: #f5f5f5;
}

.container {
	padding: 20px 16px;
}

/* 筛选器区域 */
.filter-section {
	background: white;
	border-radius: 12px;
	padding: 16px;
	margin-bottom: 20px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.filter-row {
	display: flex;
	align-items: center;
	margin-bottom: 12px;
}

.filter-row:last-child {
	margin-bottom: 0;
}

.filter-group {
	flex: 1;
	display: flex;
	align-items: center;
	margin-right: 12px;
}

.filter-label {
	font-size: 14px;
	color: #666;
	margin-right: 8px;
	white-space: nowrap;
}

.filter-input {
	flex: 1;
	padding: 8px 12px;
	border: 1px solid #ddd;
	border-radius: 6px;
	font-size: 14px;
	background: white;
}

.filter-actions {
	display: flex;
	gap: 8px;
}

.filter-btn {
	padding: 8px 16px;
	border-radius: 6px;
	font-size: 14px;
	background: #2196F3;
	color: white;
	border: none;
}

.filter-btn.secondary {
	background: #f5f5f5;
	color: #333;
}

/* 批量操作 */
.bulk-actions {
	display: flex;
	gap: 8px;
	margin-top: 12px;
	padding-top: 12px;
	border-top: 1px solid #f0f0f0;
}

.bulk-btn {
	flex: 1;
	padding: 10px;
	border-radius: 6px;
	font-size: 14px;
	background: #4CAF50;
	color: white;
	border: none;
}

.bulk-btn.primary {
	background: #FF9800;
}

/* 分页 */
.pagination {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 8px;
	padding: 20px;
	background: white;
	border-top: 1px solid #f0f0f0;
}

.page-btn {
	padding: 8px 16px;
	border-radius: 6px;
	font-size: 14px;
	background: #2196F3;
	color: white;
	border: none;
}

.page-btn:disabled {
	background: #e0e0e0;
	color: #999;
}

.page-info {
	padding: 8px 16px;
	font-size: 14px;
	color: #666;
}

/* 统计卡片 */
.stats-card {
	background: white;
	border-radius: 12px;
	padding: 20px;
	margin-bottom: 20px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	display: flex;
	justify-content: space-around;
}

.stat-item {
	text-align: center;
}

.stat-label {
	display: block;
	font-size: 14px;
	color: #666;
	margin-bottom: 8px;
}

.stat-value {
	display: block;
	font-size: 24px;
	font-weight: bold;
	color: #333;
}

.stat-value.read {
	color: #4CAF50;
}

.stat-value.unread {
	color: #FF9800;
}

/* 推送列表 */
.push-list {
	background: white;
	border-radius: 12px;
	overflow: hidden;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.push-item {
	padding: 16px;
	border-bottom: 1px solid #f0f0f0;
	transition: background-color 0.2s;
}

.push-item:last-child {
	border-bottom: none;
}

.push-item:active {
	background-color: #f8f8f8;
}

.push-item.read {
	background-color: #f5f5f5;
	opacity: 0.8;
}

.push-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 12px;
}

.push-info {
	flex: 1;
}

.task-title {
	font-size: 16px;
	font-weight: bold;
	color: #333;
	margin-bottom: 4px;
	display: block;
}

.push-time {
	font-size: 12px;
	color: #999;
}

.push-status {
	margin-left: 12px;
}

.status-badge {
	padding: 4px 8px;
	border-radius: 12px;
	font-size: 12px;
	font-weight: bold;
}

.status-pending {
	background: #FFF3CD;
	color: #856404;
}

.status-delivered {
	background: #D1ECF1;
	color: #0C5460;
}

.status-read {
	background: #D4EDDA;
	color: #155724;
}

.status-failed {
	background: #F8D7DA;
	color: #721C24;
}

.push-content {
	margin-bottom: 12px;
}

.task-description {
	font-size: 14px;
	color: #666;
	line-height: 1.5;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
}

.push-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.push-meta {
	display: flex;
	flex-wrap: wrap;
	gap: 8px;
}

.meta-item {
	font-size: 12px;
	color: #999;
	background: #f5f5f5;
	padding: 2px 6px;
	border-radius: 4px;
}

.push-actions {
	display: flex;
	gap: 8px;
}

.action-btn {
	padding: 6px 12px;
	border-radius: 6px;
	font-size: 12px;
	border: none;
	cursor: pointer;
	transition: all 0.2s;
}

.read-btn {
	background: #4CAF50;
	color: white;
}

.read-btn:active {
	background: #45a049;
}

.detail-btn {
	background: #2196F3;
	color: white;
}

.detail-btn:active {
	background: #1976D2;
}

/* 加载状态 */
.loading-container {
	text-align: center;
	padding: 40px;
}

.loading-text {
	color: #666;
	font-size: 14px;
}

/* 空状态 */
.empty-state {
	text-align: center;
	padding: 60px 20px;
}

.empty-icon {
	font-size: 48px;
	margin-bottom: 16px;
	display: block;
}

.empty-title {
	font-size: 18px;
	font-weight: bold;
	color: #333;
	margin-bottom: 8px;
	display: block;
}

.empty-subtitle {
	font-size: 14px;
	color: #666;
	line-height: 1.5;
}
</style>
